package bby.app.fettool;

import bby.app.keytools.RSA;

import java.io.*;
import java.security.KeyPair;
import java.util.Date;
import java.util.Vector;

public class MyManager extends Thread{
    ReceiverPage receiverPage;
    int have_read=1;
    long log_len=0;
    File log_file;
    BufferedReader log_reader;

    MyManager(ReceiverPage receiverPage) throws Exception{
        this.receiverPage=receiverPage;
        initFiles();
    }

    private void initFiles() {
        try {
            File dir= new File(Config.RECV_DIR);
            if (!dir.isDirectory())
                dir.mkdir();
            log_file= new File(Config.LOG_FILE);
            File lif= new File(Config.RECV_LIST_FILE);
            if (!log_file.isFile())
                log_file.createNewFile();
            if (!lif.isFile())
                lif.createNewFile();

            this.log_reader = new BufferedReader(new FileReader(log_file));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

        void logFlash(){
        long newlen=0;
        newlen=log_file.length();
        if(log_len!=newlen){
            StringBuffer stringBuffer = new StringBuffer();
            try {
                int c=0;
                while ((c=log_reader.read())!=-1){
                    stringBuffer.append((char) c);
                }
                receiverPage.addLog(stringBuffer);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                return;
            } catch (IOException e) {
                e.printStackTrace();
                return;
            }
        }
        log_len=newlen;
    }
    @Override
    public void run() {
        while (true){
            try {
                logFlash();
                sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    void print(String msg){
        receiverPage.print(msg);
    }
    boolean saveLog(){
        return receiverPage.saveLog();
    }
    Vector<RecvFile> readRecvFiles(File file){
        Vector<RecvFile> recvFiles=new Vector<>();
        try {
            BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
            String line;
            while ((line=bufferedReader.readLine())!=null){
                String record[] = line.split(" ");
                if (record.length==5){
                    File newfile=new File(Config.RECV_DIR+record[0]);//判断收到的文件是否还在
                    if (!newfile.isFile()) continue;

                    RecvFile recvFile = new RecvFile(record[0],record[1],record[2],record[3],newfile.length(),new Date());
                    //判断文件是否被解密过
                    File defile=new File(Config.RECV_DIR+recvFile.name.replace(".bbyend",""));
                    if (defile.isFile()) recvFile.isDecode=true;

                    recvFiles.add(recvFile);//Long.parseLong(record[4])

                }
                else {
                    print("记录文件错误！");
                }
            }
            return recvFiles;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            receiverPage.print("打开记录文件错误!");
        } catch (IOException e) {
            e.printStackTrace();
            receiverPage.print("读取接收记录文件错误!");
        }
        return recvFiles;
    }
    public void flashFileList() {
        File dir = new File(Config.RECV_DIR);
        if (!dir.isDirectory()) return;
        File lif= new File(Config.RECV_LIST_FILE);
        if (!lif.isFile()) return;

        receiverPage.flashFileList(readRecvFiles(lif));
    }
    public void saveFile(RecvFile recvFile){
        File lif= new File(Config.RECV_LIST_FILE);
        try {
            if (!lif.isFile())
                lif.createNewFile();

            FileWriter writer = new FileWriter(lif, true);
            String line = recvFile.name+' '+recvFile.md5+' '+recvFile.enkey+' '+recvFile.userAddress+' '+recvFile.time.getTime()+'\n';
            writer.write(line);
            writer.flush();
            writer.close();
            receiverPage.print("保存文件信息成功：");
            receiverPage.print(recvFile.toString());
        } catch (IOException e) {
            e.printStackTrace();
            receiverPage.print("保存文件信息失败！");
            return;
        }
    }
    public boolean loadKeypair(){
        File keyfile=new File(Config.KEY_FILE);
        if (!keyfile.isFile()) return false;
        else {
            try {
                BufferedReader bfr =new BufferedReader(new FileReader(keyfile));
                String pub=bfr.readLine();
                String pvt=bfr.readLine();
                receiverPage.setKeyPair(pub,pvt);
                return true;
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                return false;
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }
        }
    }
    public boolean saveKeypair(String pub,String pvt){
        File keyfile=new File(Config.KEY_FILE);
        try {
            if (!keyfile.isFile()) keyfile.createNewFile();
            BufferedWriter bfw =new BufferedWriter(new FileWriter(keyfile));
            bfw.write(pub+'\n');
            bfw.write(pvt+'\n');
            bfw.flush();
            bfw.close();
            return true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }

    }

    public void makeKeyPair(int bits) throws Exception {
        KeyPair myKeyPair = RSA.getKeyPair(bits);
        String myPublicKey=RSA.getPublicStr(myKeyPair.getPublic());
        String myPrivateKey=RSA.getPrivateStr(myKeyPair.getPrivate());
        receiverPage.print("成功创建RSA密钥对");
        receiverPage.print("公钥为："+myPublicKey);
        receiverPage.print("私钥为："+myPrivateKey);
        receiverPage.setKeyPair(myPublicKey,myPrivateKey);//设置私钥显示
        saveKeypair(myPublicKey,myPrivateKey);
    }
}
